package pingji.dao.upload.impl;

import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import pingji.dao.mapper.OrderMapper;
import pingji.dao.upload.DeleteOrderObject;
import pingji.dao.upload.UploadDao;
import pingji.pojo.Order;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Repository
@Log
public class UploadDaoImpl implements UploadDao {
    @Autowired
    OrderMapper mapper;
    @Override
    public void upload(MultipartFile file, String desc,Integer id,Integer pingjierId) throws IOException {
        String rootPath=getClass().getResource("/static").toString().replaceAll("file:/","");
        File dir=new File(rootPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String fileInResources="picture"+File.separator+System.nanoTime()+file.getOriginalFilename();
        String path=dir.getAbsolutePath()+File.separator+fileInResources;
        System.out.println(path);
        File f1=new File(path);
        if(!f1.exists()){
            f1.createNewFile();
        }
        loadFile(file,f1);
        Order o=new Order();
        o.setPath(fileInResources);
        o.setStatus("待处理");
        o.setUserId(id);
        o.setDesc(desc);
        o.setPingjiId(pingjierId);
        log.info(o.toString());
        mapper.addOrder(o);
    }

    @Override
    public void delete(Integer id, Integer userId) {
        DeleteOrderObject doo=new DeleteOrderObject();
        doo.setId(id);
        doo.setUserId(userId);
        mapper.deleteOrder(doo);
    }

    @Override
    public void shensu(Integer id, Integer userId) {
        DeleteOrderObject doo=new DeleteOrderObject();
        doo.setId(id);
        doo.setUserId(userId);
        mapper.shensu(doo);
    }

    private void loadFile(MultipartFile f1,File f2) throws IOException {
        InputStream inputStream = f1.getInputStream();
        FileOutputStream fo=new FileOutputStream(f2);
        byte []buffer=new byte[1024];
        while(true){
            int size=inputStream.read(buffer);
            if(size==-1){
                break;
            }
            fo.write(buffer,0,size);
        }
    }
}
